package com.idenger.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by zp on 17/6/1.
 */
public class TokenProcessor {
    private static TokenProcessor instance = new TokenProcessor();
    private long previous;

    protected TokenProcessor() {
    }

    public static TokenProcessor getInstance() {
        return instance;
    }

    public synchronized String generateToken(String msg, boolean timeChange) {
        try {
            long current = System.currentTimeMillis();
            if (current == previous)
                current++;
            previous = current;
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(msg.getBytes());
            if (timeChange) {
                // byte now[] = (current+"").toString().getBytes();
                byte now[] = (new Long(current)).toString().getBytes();
                md.update(now);
            }
            return toHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    private String toHex(byte buffer[]) {
        StringBuffer sb = new StringBuffer(buffer.length * 2);
        for (int i = 0; i < buffer.length; i++) {
            sb.append(Character.forDigit((buffer[i] & 240) >> 4, 16));
            sb.append(Character.forDigit(buffer[i] & 15, 16));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
//		String token = new TokenProcessor().generateToken("Vicky", true);
//		System.err.println(token);
//		String token2 = new TokenProcessor().generateToken("Vicky", false);
//		System.err.println(token2);
        String tel="18311066326";
        String token2=TokenProcessor.getInstance().generateToken(tel, true);
        System.err.println(token2);
        System.out.println(System.currentTimeMillis());//1441703026954
    }
}

